package com.example.demo.utils;

import com.example.demo.domain.DefaultFanState;
import com.example.demo.vo.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;


public class KDMOperator{


	private static String url="http://10.100.48.12:8082/kdmService/rest/1.0/kksData";
	//String url="http://10.144.136.101:8082/kdmService/rest/1.0/kksData";

    public  static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        StringBuilder result =new StringBuilder("");
        try {
            URL realUrl = new URL(url);
            //
            URLConnection conn = realUrl.openConnection();
            //
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            //
            conn.setDoOutput(true);
            conn.setDoInput(true);
            //
            out = new PrintWriter(conn.getOutputStream());
            //
            out.print(param);
            out.flush();
            //
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()),512);
            String line;
            //long st1Time=System.currentTimeMillis();
            while ((line = in.readLine()) != null) {
                result.append(line);
            }
            //long ed1Time=System.currentTimeMillis();
    		//System.out.println(ed1Time-st1Time);
        } catch (Exception e) {e.printStackTrace();}
        //
        finally{
            try{
                if(out!=null)
                    out.close();
                if(in!=null)
                    in.close();
            }catch(IOException ex){ex.printStackTrace();}
        }
        return result.toString();
    }

	/**
	 * 取最新单点数据
	 * @param kksCode
	 * @return
	 */
	public static String getSnapDataFromKDM(String kksCode) {
		String param = "method=getRTDataSnapshot&kksCodes=" + kksCode;
		String resultStr = sendPost(url, param);
		return resultStr;
	}

	/**
	 * 取历史数据，传数组含头
	 * @param kksHead
	 * @param kksCode
	 * @param startTime
	 * @param endTime
	 * @param type
	 * @return
	 */
    public static String getDataFromKDM(String kksHead,String kksCode[],long startTime,long endTime,int type){
    	if(kksCode==null||kksCode.length==0)return null;
    	StringBuilder kksParam =new StringBuilder(kksHead+kksCode[0]); 
    	if(kksCode.length>1){
    		for(int i=1;i<kksCode.length;i++){kksParam.append(","+kksHead+kksCode[i]);}
    	}
		String resultStr=getDataFromKDM(kksParam.toString(), startTime, endTime, type);
		return resultStr;
    }

	/**
	 * 取历史数据，传数组不含头
	 * @param kksCode
	 * @param startTime
	 * @param endTime
	 * @param type
	 * @return
	 */
    public static String getDataFromKDM(String kksCode[],long startTime,long endTime,int type){
    	if(kksCode==null||kksCode.length==0||kksCode[0]==null)return null;
    	StringBuilder kksParam =new StringBuilder(kksCode[0]); 
    	if(kksCode.length>1){
    		for(int i=1;i<kksCode.length;i++){kksParam.append(","+kksCode[i]);}
    	}
		String resultStr=getDataFromKDM(kksParam.toString(), startTime, endTime, type);
		return resultStr;
    }

	/**
	 * 取单点数据,发数组
	 * @param kksCode
	 * @return
	 */
	public static String getSnapDataFromKDM(String kksCode[]){
		if(kksCode==null||kksCode.length==0)return null;
		StringBuilder kksParam =new StringBuilder(kksCode[0]);
		if(kksCode.length>1){
			for(int i=1;i<kksCode.length;i++){kksParam.append(","+kksCode[i]);}
		}
		String resultStr=getSnapDataFromKDM(kksParam.toString());
		return resultStr;
	}

	/**
	 * 取历史数据，传单条
	 * @param kksCode
	 * @param startTime
	 * @param endTime
	 * @param type
	 * @return
	 */
    public static String getDataFromKDM(String kksCode,long startTime,long endTime,int type){
    	String param ="method=getRTDataHistory&kksCodes="+kksCode+"&startTime="+startTime+"&endTime="+endTime+"&resultType="+type;
    	//System.out.println(param);
    	String resultStr=sendPost(url,param);
    	return resultStr;
    }

	/**
	 * 取块数据
	 * @param kksCode
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	public static String getKDMSection(String kksCode,long startTime,long endTime){
		String jsonResult=KDMOperator.getDataFromKDM(kksCode,startTime,endTime,1);
		RTDData rtdData=null;
		try {
			rtdData=JsonOperator.getRTDateByJsonString(jsonResult);
		} catch (IOException e) {
			e.printStackTrace();
		}
		if(rtdData.getRTDataSets().length==0){
			return "";
		}
		int dotNum=rtdData.getRTDataSets()[0].getRTDataValues().length;
		if(dotNum==0){
			return "";
		}
		long timeSection=rtdData.getRTDataSets()[0].getRTDataValues()[dotNum-1].getTime();

		String jsonReturn=KDMOperator.getDataFromKDM(kksCode,timeSection,timeSection,2);
		RTDataSection sectionData=null;
		try {
			sectionData=JsonOperator.getRTDataSectionByJsonString(jsonReturn);
		} catch (IOException e) {
			e.printStackTrace();
		}
		RTDataSetSection[] rtDataSetSections=sectionData.getRTDataSets();
		if(rtDataSetSections.length==0)return "";
		RTDataValueSection[] rtDataValueSections=rtDataSetSections[0].getRTDataValues();
		if(rtDataValueSections.length==0)return "";
		String finalJson=new String(rtDataValueSections[0].getValue());

		//double values[][]=new Gson().fromJson(finalJson,double[][].class);
    	return finalJson;
	}

	/**
	 * 封装了要取大量KDM机数量的代码
	 * @param kksList
	 * @param fanStateMap
	 * @param timeFlag
	 * @return
	 */
	static public Map<String,DefaultFanState> getStateListByKKSListAndFanList(List<String> kksList, Map<String,DefaultFanState> fanStateMap,int timeFlag){
		Map<String,Integer> typeMap=new HashMap<>();
		List<String> allKKSCodeList=new ArrayList<>();
		/*时间限定*/
		char calendarFlag;
		switch (timeFlag) {
			case 0:
				calendarFlag = 'D';
				break;
			case 1:
				calendarFlag = 'W';
				break;
			case 2:
				calendarFlag = 'M';
				break;
			case 3:
				calendarFlag = 'Y';
				break;
			default:
				calendarFlag = ' ';
				break;
		}
		long[] time=null;
		if(calendarFlag!=' '){
			time=TimeManager.timeChoice(Calendar.getInstance(),calendarFlag);
		}
		int flag=0;
		for(String kksCode:kksList){
			typeMap.put(kksCode,flag++);
			for (Map.Entry<String,DefaultFanState> entry : fanStateMap.entrySet()){
				allKKSCodeList.add(entry.getKey()+kksCode);
			}
		}
		for(Map.Entry<String,DefaultFanState> entry:fanStateMap.entrySet()){
			RTDataValueNew[] rtDataValueNews=new RTDataValueNew[flag];
			for(int i=0;i<flag;i++){
				rtDataValueNews[i]=new RTDataValueNew();
			}
			entry.getValue().setStateList(rtDataValueNews);
		}
		// /kdm机限制每次最多传1000个kks码，将多出的分为多个数组
		ArrayList<ArrayList<String>> kksDoubleList= KKSCodeSplit.kksCodeSplitFuction((ArrayList<String>) allKKSCodeList,1000);
		for(ArrayList<String> pieceKKSList:kksDoubleList){
			String[] pieceKKSArray=new String[pieceKKSList.size()];
			pieceKKSArray=pieceKKSList.toArray(pieceKKSArray);
			String jsonResult=null;
			if(timeFlag==-1){
				jsonResult=KDMOperator.getSnapDataFromKDM(pieceKKSArray);
			}else{
				jsonResult=KDMOperator.getDataFromKDM(pieceKKSArray,time[0],time[1],2);
			}
			RTDData rtdData=null;
			try {
				rtdData=JsonOperator.getRTDateByJsonString(jsonResult);
			} catch (IOException e) {
				e.printStackTrace();
			}
			RTDataSetNew[] rtDataSetNews=rtdData.getRTDataSets();
			if(rtDataSetNews==null){
				System.out.println("cannot get any result!!");
				continue;
			}
			for(RTDataSetNew rtDataSet:rtDataSetNews){
				String allKKS=rtDataSet.getKksCode();
				String rightKKSCode=allKKS.substring(8);
				String leftKKSCode=allKKS.substring(0,8);
				double value=0;
				long thisTime=0;
				RTDataValueNew[] rtDataValues=rtDataSet.getRTDataValues();
				if(rtDataValues==null){
					continue;
				}
				if(rtDataValues.length>0){
					value=rtDataValues[rtDataValues.length-1].getValue();
					thisTime=rtDataValues[rtDataValues.length-1].getTime();
				}
				DefaultFanState defaultFanState=fanStateMap.get(leftKKSCode);
				int type=typeMap.get(rightKKSCode);
				defaultFanState.getStateList()[type].setValue(value);
				defaultFanState.getStateList()[type].setTime(thisTime);
			}
		}

		return fanStateMap;
	}

	/**
	 * 根据时间段，获取状态列表
	 * @param kksList
	 * @param fanStateMap
	 * @param startTime
	 * @param endTime
	 * @return
	 */
	static public Map<String,DefaultFanState> getStateListByKKSListAndFanList(List<String> kksList, Map<String,DefaultFanState> fanStateMap,long startTime,long endTime){
		Map<String,Integer> typeMap=new HashMap<>();
		List<String> allKKSCodeList=new ArrayList<>();
		int flag=0;
		for(String kksCode:kksList){
			typeMap.put(kksCode,flag++);
			for (Map.Entry<String,DefaultFanState> entry : fanStateMap.entrySet()){
				allKKSCodeList.add(entry.getKey()+kksCode);
			}
		}
		for(Map.Entry<String,DefaultFanState> entry:fanStateMap.entrySet()){
			RTDataValueNew[] rtDataValueNews=new RTDataValueNew[flag];
			for(int i=0;i<flag;i++){
				rtDataValueNews[i]=new RTDataValueNew();
				rtDataValueNews[i].setValue(0);
			}
			DefaultFanState defaultFanState=entry.getValue();
			defaultFanState.setStateList(rtDataValueNews);
			entry.setValue(defaultFanState);
		}
		// /kdm机限制每次最多传1000个kks码，将多出的分为多个数组
		ArrayList<ArrayList<String>> kksDoubleList= KKSCodeSplit.kksCodeSplitFuction((ArrayList<String>) allKKSCodeList,1000);
		for(ArrayList<String> pieceKKSList:kksDoubleList){
			String[] pieceKKSArray=new String[pieceKKSList.size()];
			pieceKKSArray=pieceKKSList.toArray(pieceKKSArray);
			String jsonResult=null;
			jsonResult=KDMOperator.getDataFromKDM(pieceKKSArray,startTime,endTime,2);

			RTDData rtdData=null;
			try {
				rtdData=JsonOperator.getRTDateByJsonString(jsonResult);
			} catch (IOException e) {
				e.printStackTrace();
			}
			if(rtdData==null){
				continue;
			}
			RTDataSetNew[] rtDataSetNews=rtdData.getRTDataSets();
			if(rtDataSetNews==null){
				System.out.println("cannot get any result!!");
				continue;
			}
			for(RTDataSetNew rtDataSet:rtDataSetNews){
				String allKKS=rtDataSet.getKksCode();
				String rightKKSCode=allKKS.substring(8);
				String leftKKSCode=allKKS.substring(0,8);
				double value=0;
				long thisTime=0;
				RTDataValueNew[] rtDataValues=rtDataSet.getRTDataValues();
				if(rtDataValues==null){
					continue;
				}
				DefaultFanState defaultFanState=fanStateMap.get(leftKKSCode);
				int type=typeMap.get(rightKKSCode);
				if(rtDataValues.length>0){
					value=rtDataValues[rtDataValues.length-1].getValue();
					thisTime=rtDataValues[rtDataValues.length-1].getTime();
					defaultFanState.getStateList()[type].setValue(value);
					defaultFanState.getStateList()[type].setTime(thisTime);
					continue;
				}
				defaultFanState.getStateList()[type]=null;
			}
		}

		return fanStateMap;
	}
    

    
	public static void main(String[] args) {
		String s = "NM006W01MZZ00000LA011CD01";

		Calendar calendar = Calendar.getInstance();//获取时间戳
		long[] timeArray = TimeManager.timeChoice(calendar, 'M');
		//System.out.println(getKDMSection(s,timeArray[0],timeArray[1]));
		System.out.println(getSnapDataFromKDM(s));



	}


}
